<template>
  <main
    style="
      width: 100%;
      height: 280px;
      background-color: rgba(255, 255, 203, 0.5);
    "
  >
    <div style="width: 100%; height: 32px">
      <div>
        <el-input
          v-model="keysinwordss"
          style="width: 100%"
          placeholder="请输入曲名"
          class="input-with-select"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="类型" style="width: 75px">
              <el-option label="曲名" value="1" />
              <el-option label="曲名" value="2" />
              <el-option label="曲名" value="3" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" @click="handleSearch()" />
            <el-button
              :icon="RefreshRight"
              style="margin-left: 15px"
              @click="deli()"
            />
          </template>
        </el-input>
      </div>
    </div>
    <div style="width: 100%; height: 224px; background-color: antiquewhite">
      <el-table
        :data="searchResults"
        style="width: 100%; height: 100%"
        size="small"
        empty-text="暂无文件"
      >
        <el-table-column
          label="歌曲名称"
          width="210"
          align="left"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit()"> 试听 </el-button>
            <el-button
              :icon="CaretRight"
              type="success"
              size="small"
              circle
              plain
              @click="handleDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>
        <div
      style="
        width: 100%;
        height: 24px;
        background-color: antiquewhite;
        display: flex;
        justify-content: center;
        align-items: center;
      "
    >
      <el-pagination
        background
        size="small"
        layout="prev, pager, next"
        :total="pagination.total"
        :pager-count="5"
      />
    </div>
  </main>
</template>

<script lang="ts" setup>
import { Search, RefreshRight, CaretRight } from "@element-plus/icons-vue";
import { ref, reactive, onMounted } from "vue";
import { message } from "@/utils/messages";
import { useRouter } from "vue-router";
const router = useRouter();
const txtFileObjects = ref<{ name: string }[]>([]);
const searchResults = ref<{ name: string }[]>([]);
const keysinwordss = ref("");
const select = ref("1");
const props = defineProps({
  filecarlist: {
    type: Array as () => { name: string }[], // 指定数组元素的类型
    required: false, // 是否必填
    default: () => [] // 默认值
  }
})
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1,
});

const handleSearch = () => {
  const keyword = keysinwordss.value.toLowerCase();
  if (keyword) {
    searchResults.value = txtFileObjects.value.filter((item) =>
      item.name.toLowerCase().includes(keyword),
    );
  } else {
    searchResults.value = [];
  }
};

const deli = () => {
  keysinwordss.value = "";
  searchResults.value = txtFileObjects.value;
};
const handleEdit = () => {
  message("没有开放哦，桀桀桀", "success");
};

const handleDelete = async (row: any) => {
    let scoprod = await bakutf16le(row.name);
  if (scoprod) {
    onFileContent(scoprod);
  }
  //   try {
  //     const response = await fetch(`/src/assets/scores/${row.name}.txt`);
  //     if (!response.ok) {
  //       throw new Error(`无法读取文件: ${row.name}.txt`);
  //     }
  //     const text = await response.text();
  //     console.log(text);
  //   } catch (error) {
  //     console.error('读取文件时出错:', error);
  //   }
};
const bakutf16le = async (name: string) => {
  try {
    const response = await fetch(`/src/assets/scores/${name}.txt`);
    if (!response.ok) {
      throw new Error(`无法读取文件: ${name}.txt`);
    }
    const buffer = await response.arrayBuffer();
    const encodings = ["utf-16le"];
    for (const encoding of encodings) {
      try {
        const decoder = new TextDecoder(encoding);
        const text = decoder.decode(buffer);
        if (/[^\x00-\x7F]/.test(text)) {
          return text;
        }
      } catch (error) {
        message(`使用 ${encoding} 编码解码失败`, "warning");
        return false;
      }
    }
    message(`所有编码尝试均失败：`, "warning");
    return false;
  } catch (error) {
    message(`读取文件时出错`, "warning");
    return false;
  }
};
function onFileContent(content: string) {
  try {
    router.push({
      path: "/music",
      query: { content },
    });
  } catch (e) {
    message("非合法 TXT 谱，重新选择", "warning");
  }
}
onMounted(async () => {
  txtFileObjects.value = props.filecarlist;
  searchResults.value = props.filecarlist;
});
</script>
